package com.shuqi.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

/**
 * 读写文件
 * 
 * @author linyuren
 * 
 */
public class LocalDataFileManager {

    /** 保存文件到本地 */
    public static void saveLocalDataFile(String fileName, byte[] data, Context context) {
        FileOutputStream fos = null;
        try {
            fos = context.openFileOutput(fileName + ".dat", Context.MODE_PRIVATE);
            fos.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /** 读取本地文件 */
    public static byte[] loadLocalDataFile(String fileName, Context context) {
        File f = context.getFileStreamPath(fileName + ".dat");
        if (!f.exists()) {
            return null;
        }
        FileInputStream fis = null;
        try {
            fis = context.openFileInput(fileName + ".dat");
            byte[] reader = new byte[fis.available()];
            while (fis.read(reader) != -1);
            return reader;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
